package com.kiwi.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by bjwangxingchen on 2017/6/23.
 */
public class HostUtil {
    /*
    获取目的ip
     */
    public static String getServerStringIp(String domain) {
        InetAddress[] array = gerServerIp(domain);
        String ip = "";
        if (array == null) {
            return null;
        }
        for (int i = 0; i < array.length; i++) {
            ip = ip + "ip" + i + " = " + array[i].getHostAddress() + " | ";
        }
        return ip;
    }

    public static InetAddress[] gerServerIp(String domain) {
        InetAddress[] servers = null;
        try {
            servers = InetAddress.getAllByName(domain);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return servers;

    }

    public static String getLocalHostIP() {
        String ip;
        try {
            /**返回本地主机。*/
            InetAddress addr = InetAddress.getLocalHost();
            /**返回 IP 地址字符串（以文本表现形式）*/
            ip = addr.getHostAddress();
        } catch (Exception ex) {
            ip = "";
        }
        return ip;
    }

    public static String getLocalHostName() {
        String hostName;
        try {
            /**返回本地主机。*/
            InetAddress addr = InetAddress.getLocalHost();
            /**获取此 IP 地址的主机名。*/
            hostName = addr.getHostName();
        } catch (Exception ex) {
            hostName = "";
        }

        return hostName;
    }

    /**
     * 获得本地所有的IP地址
     *
     * @return
     */
    public static String[] getAllLocalHostIP() {
        String[] ret = null;
        try {
            /**获得主机名*/
            String hostName = getLocalHostName();
            if (hostName.length() > 0) {
                /**在给定主机名的情况下，根据系统上配置的名称服务返回其 IP 地址所组成的数组。*/
                InetAddress[] addrs = InetAddress.getAllByName(hostName);
                if (addrs.length > 0) {
                    ret = new String[addrs.length];
                    for (int i = 0; i < addrs.length; i++) {
                        /**.getHostAddress()   返回 IP 地址字符串（以文本表现形式）。*/
                        ret[i] = addrs[i].getHostAddress();
                    }
                }
            }
        } catch (Exception ex) {
            ret = null;
        }
        return ret;
    }
}